package nj.yb.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.sctp.nio.NioSctpServerChannel;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

public class ChatServer {

    private int port;

    public ChatServer(int port) {
        this.port = port;
    }

    public void run(){
        //创建两个事件循环组
        /**
         * 老板组负责接受连接
         */
        EventLoopGroup bossGroup = new NioEventLoopGroup();

        /**
         * 工人组负责处理连接
         */
        EventLoopGroup workerGroup = new NioEventLoopGroup();


        try {
            //服务器启动器
            ServerBootstrap bootstrap = new ServerBootstrap();
            //绑定事件循环组
            bootstrap.group(bossGroup,workerGroup)
                    //指定服务器通道实现
                    .channel(NioServerSocketChannel.class)
                    //指定连接队列的大小（tcp缓存区）
                    .option(ChannelOption.SO_BACKLOG,128)
                    //保持连接
                    .childOption(ChannelOption.SO_KEEPALIVE,true)
                    //为 每个新建立的客户端连接 配置 IO 处理器
                    .childHandler(new ChannelInitializer<SocketChannel>() {

                        protected void initChannel(SocketChannel ch) throws Exception {
                            //添加字符串编解码器（自动处理字符串与字节转换）
                            ch.pipeline().addLast(new StringDecoder());
                            ch.pipeline().addLast(new StringEncoder());
                            //添加自定义业务处理器
                            ch.pipeline().addLast(new ChatServerHandler());
                        }
                    });
            System.out.println("服务器启动，监听端口：" +port);
            //绑定端口，等待同步成功
            ChannelFuture future = bootstrap.bind(port).sync();

            //阻塞主线程，直到服务器通道关闭
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }

    public static void main(String [] args){
        new ChatServer(8081).run();

    }


}
